using System;
using System.Linq;
using System.Web.Mvc;
using viBook.Common;
using viBook.Models;

namespace viBook.Controllers
{
    public class CommentsController : BaseController
    {
        #region Constructors and Repository vars

        private readonly ICommentRepository _commentRepository;

        public CommentsController()
            : this(new CommentRepository())
        {
        }

        public CommentsController(ICommentRepository commentRepository)
        {
            this._commentRepository = commentRepository;
        }

        #endregion

        [HttpPost, Authorize]
        public JsonResult Create(ChapterComment chapterComment)
        {
            if (ModelState.IsValid)
            {
                _commentRepository.InsertOrUpdate(chapterComment);
                _commentRepository.Save();
                return _successFeedback;
            }
            return _failedFeedback;
        }

        [HttpPost, Authorize]
        public JsonResult Edit(ChapterComment chapterComment)
        {
            _commentRepository.InsertOrUpdate(chapterComment);
            _commentRepository.Save();
            return _successFeedback;

        }

        [HttpPost, ActionName("Delete"), Authorize]
        public JsonResult DeleteConfirmed(int id)
        {
            _commentRepository.Delete(id);
            return _successFeedback;
        }

        [HttpPost, Authorize]
        public JsonResult VoteUp(int id)
        {
            _commentRepository.VoteUp(id);
            return _successFeedback;
        }

        [HttpPost, Authorize]
        public JsonResult VoteDown(int id)
        {
            _commentRepository.VoteDown(id);
            return _successFeedback;
        }

        [HttpPost, Authorize]
        public JsonResult ReportComment(int id)
        {
            _commentRepository.Report(id, ExtendedIdentity.Id);
            return _successFeedback;
        }

        [HttpPost]
        public JsonResult FetchNextCommentPage(int chapterId, int pageNumber)
        {
            var comments = _commentRepository.FetchCommentsByPage(chapterId, pageNumber).ToList();
            return Json(new
            {
                isSuccess = true,
                comments = comments.Select(c => new
                {
                    id = c.Id,
                    username = ExtendedIdentity.Name,
                    content = c.Content,
                    createdDate = c.CreatedDate,
                    vote = c.Vote,
                    isVotedUp = c.IsVotedUp,
                    isVotedDown = c.IsVotedDown,
                    isReported = c.IsReported
                })
            });
        }
    }
}

